package com.sumainfor.pc.gmio.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.FinancialProviderMapper;
import com.sumainfor.pc.gmio.feign.BaseFeignZuul;
import com.sumainfor.pc.gmio.feign.BasePcEpcFeign;
import com.sumainfor.pc.gmio.feign.BasePcMktFeign;
import com.sumainfor.pc.gmio.feign.BaseTenantFeign;
import com.sumainfor.pc.gmio.service.FinancialProviderService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-04-18 10:25
 * 财务部服务提供者服务
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class FinancialProviderServiceImpl implements FinancialProviderService {

    @Autowired
    private FinancialProviderMapper fpm;

    @Autowired
    private BasePcMktFeign mktFeign;

    @Autowired
    private BaseTenantFeign tenantFeign;

    @Autowired
    private BaseFeignZuul zuul;

    @Autowired
    private BasePcEpcFeign epcFeign;

    /**
     * 查询唐巢收入信息 房租 公共事业 维修 夜间开门 退租 其他 主页数据
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult selectOrderInTableList(Page page, Map<String, Object> params) {
        //获取所有的房源信息 id
        List<String> housingList = fpm.selectHousingList(MapUtils.getString(params, "BiType"));
        //调用远程服务 市场部 获取最终筛选的结果
        if (CollectionUtils.isEmpty(housingList)) {
            return JsonResult.success(page);
        }
        params.put("hids", housingList);
        List<Map<String, Object>> ids = mktFeign.filterHousingData(params);
        if (CollectionUtils.isEmpty(ids)) {
            return JsonResult.success(page);
        }
        //有数据了 进行查询
        params.put("hids", ids.stream().map(item -> MapUtils.getString(item, "HouInfoId")).collect(Collectors.toList()));
        IPage<Map<String, Object>> pageData = fpm.selectOrderIn(page, params);
        //数据封装
        for (Map<String, Object> map : pageData.getRecords()) {

            //付款公司名称：
            Integer corId = MapUtils.getInteger(map, "CorId");
            Map<String, Object> areaMap = zuul.getAreaInfoById(corId);
            map.put("AreaName", MapUtils.getString(areaMap, "name"));

            // 获取租客姓名 手机号
            String tenId = MapUtils.getString(map, "TenId");
            if (StringUtils.isBlank(tenId)) {
                throw new TCException("租客编号为空");
            }
            JsonResult<JSONObject> tenResult = tenantFeign.getWxInfoByTenId(tenId);
            if (tenResult.isSuccess() == false) {
                throw new TCException("用户不存在");
            }
            String realName = (String) tenResult.getResult().get("realName");
            if (StringUtils.isBlank(realName)) {
                realName = tenResult.getResult().getString("tenName");
            }
            map.put("TenName", realName);
            map.put("TenPhone", tenResult.getResult().getString("tenPhone"));
            //支付方式
            String payType = "";
            Integer payMode = MapUtils.getInteger(map, "PayMode", -10);
            switch (payMode) {
                case 0:
                    payType = "线下支付";
                    break;
                case 1:
                    payType = "微信";
                    break;
                case 2:
                    payType = "支付宝";
                    break;
                default:
                    payType = "未支付";
            }
            map.put("PayMode", payType);
            //审核人
            map.put("AuditName", "");
            if (payMode.equals(0)) {
                map.put("AuditName", "系统");
            } else {
                String auditId = MapUtils.getString(map, "AuditId");
                if (StringUtils.isNotBlank(auditId)) {
                    //远程服务调用 获取审核人信息
                    JsonResult<List<Map<String, Object>>> result = zuul.getUserInfo(Arrays.asList(auditId));
                    if (!result.isSuccess()) {
                        Assert.state(false, "获取用户信息失败");
                        if (CollectionUtils.isEmpty(result.getResult())) {
                            Assert.state(false, "获取用户信息失败");
                        }
                        map.put("AuditName", result.getResult().get(0).get("username"));
                    }
                }
            }
            //获得关联合同编号
            map.put("PaId", "");
            for (Map<String, Object> idMap : ids) {
                if (Objects.equals(idMap.get("HouInfoId"), map.remove("HouInfoId"))) {
                    map.put("PaId", idMap.get("PaId"));
                    break;
                }
            }

            //获取合同
            map.put("PDFUrl", "");
            String sourceId = MapUtils.getString(map, "Source");
            //查询获取合同文件信息
            JsonResult<String> pdfLinkJson = mktFeign.getPactPDFLink(sourceId);
            if (pdfLinkJson.isSuccess()) {
                String pdfUrl = pdfLinkJson.getResult();
                map.put("PDFUrl", pdfUrl);
            }


        }
        return JsonResult.success(pageData);
    }

    /**
     * 查询唐巢支出账单
     *
     * @param page
     * @param params Status  BiOutType 不可为空
     * @return
     */
    @Override
    public JsonResult selectOrderOutTableList(Page page, Map<String, Object> params) {
        Integer type = MapUtils.getInteger(params, "BiOutType");
        JsonResult result = JsonResult.errorForEmpty();
        //账单类型  1.业主   2.供应商  3.退租账单   4.公共事业费
        switch (type) {
            case 1:
                // TODO: 2019/4/20 搁置 冲突
                break;
            case 2:
                return orderOutForSup(page, params);
            case 3:
                return orderOutForBack(page, params);
            case 4:
                return orderOutForPublic(page, params);
            default:
                result = JsonResult.error("没有这个类型");
        }
        return result;
    }

    /**
     * 废弃
     *
     * @param page
     * @param params
     * @return

     @Deprecated private JsonResult<IPage<Map<String, Object>>> orderOutForOwner(Page page, Map<String, Object> params) {
     //获取所有的房源信息 id
     List<String> housingList = fpm.selectOwnerOutListForHousingId(MapUtils.getString(params, "BiOutType"), MapUtils.getInteger(params, "BiOutType"));
     //调用远程服务 市场部 获取最终筛选的结果
     if (CollectionUtils.isEmpty(housingList)) {
     return JsonResult.success(page);
     }
     params.put("hids", housingList);
     List<Map<String, Object>> ids = mktFeign.filterHousingData(params);
     if (CollectionUtils.isEmpty(ids)) {
     return JsonResult.success(page);
     }
     //有数据了 进行查询
     params.put("ids", ids.stream().map(item -> MapUtils.getString(item, "HouInfoId")).collect(Collectors.toList()));
     IPage<Map<String, Object>> dataList = fpm.selectOwnerOutList(page, params);
     for (Map<String, Object> map : dataList.getRecords()) {
     //获取租客信息数据
     Map<String, Object> ownerInfo = mktFeign.getOwnerInfoByParams(CustomMap.create("OwId", map.get("StemId")));
     if (MapUtils.isEmpty(ownerInfo)) {
     throw new TCException("获取业主信息失败");
     }
     //获取合同信息
     Map<String, Object> pactInfo = mktFeign.selectOwnerPactInfo((String) map.get("StemId"));
     if (MapUtils.isEmpty(pactInfo)) {
     throw new TCException("获取业主合同失败");
     }
     CustomMap customMap = CustomMap.create()
     .put("OwName", ownerInfo.get("OwName"))
     .put("OwPhone", ownerInfo.get("OwPhone"))
     .put("OwDeId", pactInfo.get("OwDeId"))
     .put("PayBank", pactInfo.get("PayBank"))
     .put("PayAccount", pactInfo.get("PayAccount"))
     .put("LateDay", map.get("PayAccount"))
     .put("LateDay", map.get("PayAccount"))
     .put("BiMoney", map.get("BiMoney"));
     }
     return JsonResult.success();
     }*/


    /**
     * 查询供应商的信息
     *
     * @param page
     * @param params
     * @return
     */
    private JsonResult orderOutForSup(Page page, Map<String, Object> params) {
        String search = MapUtils.getString(params, "search");
        if (StringUtils.isNotBlank(search)) {
            //1. 查询所有的编号
            List<String> remitIds = fpm.selectRemitListForSup(MapUtils.getInteger(params, "Status"), "Relation", "2");
            if (CollectionUtils.isEmpty(remitIds)) {
                return JsonResult.success(page);
            }
            //2. 调用服务进行筛选数据
            List<String> ids = epcFeign.searchSupNameToRemitIds(CustomMap.create("supName", search).put("remitIds", remitIds));
            params.put("ids", ids);
        }
        //查询结果
        IPage<Map<String, Object>> dataList = fpm.selectOrderOutListForSup(page, params);
        for (Map<String, Object> map : dataList.getRecords()) {

            //付款公司名称：
            Integer corId = MapUtils.getInteger(map, "CorId");
            Map<String, Object> areaMap = zuul.getAreaInfoById(corId);
            map.put("AreaName", MapUtils.getString(areaMap, "name"));

            Map<String, Object> supInfo = epcFeign.getSupplierOrderInfoForRemit(MapUtils.getString(map, "Relation"));
            if (MapUtils.isEmpty(supInfo)) {
                return JsonResult.error("查询失败");
            }
            map.putAll(supInfo);
            //查询决算数据  在财务进行查询的操作
            //查询申请人 数据
            map.put("CreateName", "");
            //审批人的名称
            map.put("AuditName", "");
            String createId = MapUtils.getString(map, "Create", "");
            String uploadUserId = MapUtils.getString(map, "UploadUserId", "");
            JsonResult<List<JSONObject>> userInfo = zuul.getUserInfo(Arrays.asList(createId, uploadUserId));
            if (userInfo.isSuccess() && CollectionUtils.isNotEmpty(userInfo.getResult())) {
                for (JSONObject object : userInfo.getResult()) {
                    if (object.getString("user_id").equals(createId)) {
                        map.put("CreateName", object.getString("username"));
                    } else {
                        map.put("AuditName", object.getString("username"));
                    }
                }
            }
            DateUtils.formatDateByMap(map);
        }
        return JsonResult.success(dataList);
    }


    /**
     * 查询退租账单的信息
     *
     * @param page
     * @param params
     * @return
     */
    private JsonResult orderOutForBack(Page page, Map<String, Object> params) {
        String search = MapUtils.getString(params, "search", "");
        //1. 查询所有的编号
        List<String> tenids = fpm.selectRemitListForSup(MapUtils.getInteger(params, "Status"), "StemId", "3");
        if (CollectionUtils.isEmpty(tenids)) {
            return JsonResult.success(page);
        }
        //调用服务查询
        List<Map<String, Object>> infoList = tenantFeign.selectTenantInfo(CustomMap.create("search", search).put("ids", tenids));
        if (CollectionUtils.isEmpty(infoList)) {
            return JsonResult.error("查询失败");
        }
        List<String> tIds = infoList.stream().map(item -> MapUtils.getString(item, "TenId")).collect(Collectors.toList());
        params.put("ids", tIds);
        IPage<Map<String, Object>> dataList = fpm.selectOrderOutListForBack(page, params);
        for (Map<String, Object> map : dataList.getRecords()) {
            for (Map<String, Object> infoMap : infoList) {
                if (Objects.equals(map.get("StemId"), infoMap.get("TenId"))) {

                    //付款公司名称：
                    Integer corId = MapUtils.getInteger(map, "CorId");
                    Map<String, Object> areaMap = zuul.getAreaInfoById(corId);
                    map.put("AreaName", MapUtils.getString(areaMap, "name"));

                    map.putAll(infoMap);
                    //处理逻辑操作
                    String uploadUserId = MapUtils.getString(map, "UploadUserId", "");
                    String launchId = MapUtils.getString(map, "LaunchId", "");
                    String auditId = MapUtils.getString(map, "AuditId", "");
                    List<String> uIds = Lists.newArrayList(uploadUserId, launchId, auditId);

                    map.put("ActionUserName", "");
                    map.put("LaunchUserName", "");
                    map.put("AuditUserName", "");

                    JsonResult<List<JSONObject>> userInfo = zuul.getUserInfo(uIds);
                    if (userInfo.isSuccess() && CollectionUtils.isNotEmpty(userInfo.getResult())) {
                        for (JSONObject object : userInfo.getResult()) {
                            if (object.getString("user_id").equals(uploadUserId)) {
                                map.put("ActionUserName", object.getString("username"));
                            } else if (object.getString("user_id").equals(launchId)) {
                                map.put("ActionUserName", object.getString("LaunchUserName"));
                            } else {
                                map.put("ActionUserName", object.getString("AuditUserName"));
                            }
                        }
                    }
                    DateUtils.formatDateByMap(map);
                    break;
                }
            }
        }
        return JsonResult.success(dataList);
    }

    /**
     * 查询公共事业费 支出账单
     *
     * @param page
     * @param params
     * @return
     */
    private JsonResult orderOutForPublic(Page page, Map<String, Object> params) {
        if (!FieldCheckUtil.isMapFieldNotNull(params, "PubType")) {
            return JsonResult.errorForEmpty();
        }
        IPage<Map<String, Object>> dataList = fpm.selectOrderOutListForPublic(page, params);
        for (Map<String, Object> map : dataList.getRecords()) {

            //付款公司名称：
            Integer corId = MapUtils.getInteger(map, "CorId");
            Map<String, Object> areaMap = zuul.getAreaInfoById(corId);
            map.put("AreaName", MapUtils.getString(areaMap, "name"));

            //查询项目 服务中心名称
            Map<String, Object> hInfo = mktFeign.selectHousingInfo(MapUtils.getString(map, "HouInfoId"));
            if (MapUtils.isEmpty(hInfo)) {
                return JsonResult.error("查询房源信息失败");
            }
            map.putAll(hInfo);
            DateUtils.formatDateByMap(map);
        }
        return JsonResult.success(dataList);
    }


    /**
     * 唐巢支付 设置支付成功接口
     *
     * @param biOutId
     * @return
     */
    @Override
    public JsonResult setPayDone(String biOutId) {
        int row = fpm.updateBillOutData(ParamsCommon.commonUpdateParms(CustomMap.create()
                        .put("BiOutId", biOutId)
                        .put("PayTime", DateTime.now().toDate())
                        .put("UploadUserId", ContextUtils.getUserId())
                        .put("Status", 2)
                , getClass()));
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }

}
